package com.ch3cooh.server2.service;

import com.ch3cooh.common.service.KeyConstant;
import com.ch3cooh.common.service.RedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class HelloService {

    @Autowired
    StringRedisTemplate redisTemplate;

    public boolean getLockAndSleep(int sleepTime){
        RedisLock redisLock = new RedisLock(redisTemplate, KeyConstant.KEY_1, 10, 3000);
        if( redisLock.tryLock() ){
            System.out.println("server1 做了很多事情 ... ");
            try {
                Thread.sleep(sleepTime / 2);
                redisLock.unlock();
                System.out.println("server1 完成任务并释放了锁 ");
                return true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }



}
